package com.magina.antiPro.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Aspect
@Component
public class NumberFormatAnnoAspect {
    final static Logger log = LoggerFactory.getLogger(NumberFormatAnnoAspect.class);

    ThreadLocal<Long> beginTime = new ThreadLocal<>();

    @Pointcut("@annotation(numberFormatAnno)")
    public void cut(NumberFormatAnno numberFormatAnno) {
    }

    @Before("cut(numberFormatAnno)")
    public void doBefore(JoinPoint joinPoint, NumberFormatAnno numberFormatAnno) {
        // 记录请求到达时间
        beginTime.set(System.currentTimeMillis());
        String str = joinPoint.getSignature().getName();
//        ReflectionUtils.(bean.getClass());
        Field[] fields = NumberFormatAnno.class.getDeclaredFields();
        for(Field field : fields){
            //判断属性是否标注了@ProductAnnotation注解
            boolean fieldHasAnno = field.isAnnotationPresent(NumberFormatAnno.class);
            if(fieldHasAnno){
                //获取@ProductAnnotation注解
                NumberFormatAnno anno = field.getAnnotation(NumberFormatAnno.class);
                //获取@ProductAnnotation注解 参数值
                String name = anno.note();
                System.out.println(field);
                System.out.println(name);
//                String publishYear = product.publishYear();
                //ProductAnnotation.Type type = product.productType();
//                System.out.println("[" + field.getName() + "] " + name + ","+ type + "," + publishYear);
            }
        }
        log.info("magina note:{}", numberFormatAnno.note());
    }

    @Around("cut(numberFormatAnno)")
    public Object Interceptor(ProceedingJoinPoint pjp, NumberFormatAnno numberFormatAnno){
        Object result = null;
        numberFormatAnno.note();
        Object[] args = pjp.getArgs();
        if(args != null && args.length >0) {
            String deviceId = (String) args[0];
            if(!"03".equals(deviceId)) {
                return "no anthorization";
            }
        }
        try {
            result =pjp.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
    }

    @After("cut(numberFormatAnno)")
    public void doAfter(NumberFormatAnno numberFormatAnno) {
        log.info("magina statistic time:{}, note:{}", System.currentTimeMillis() - beginTime.get(), numberFormatAnno.note());
    }
}
